package com.lagou.web;

import com.lagou.dao.StudentDao;
import com.lagou.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @author Administrator
 */
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Student student = new Student();
        System.out.println("-----update servlet--- id ");
        String idStr = req.getParameter("id");
        if( idStr == null || idStr.isEmpty()){
            System.out.println("请输入学生信息");
            req.getRequestDispatcher("/listStu").forward(req,resp);
        }

        int id = Integer.parseInt(req.getParameter("id"));
        System.out.println("-----update servlet--- id = "+id);
        String name = req.getParameter("name");
        System.out.println(name);
        String sex = req.getParameter("sex");
        System.out.println(sex);
        String str = req.getParameter("birthday");

        if( name == null || sex == null || str == null){
            System.out.println("请输入学生信息");
            req.getRequestDispatcher("/listStu").forward(req,resp);
        }

        // String 类型按照 yyyy-MM-dd 的格式转换为 java.util.Date 类
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {

            Date date = simpleDateFormat.parse(str);
            student.setId(id);
            student.setStname(name);
            student.setSex(sex);
            student.setBirthday(date);
            System.out.println(student);
            new StudentDao().update(student);

            req.getRequestDispatcher("/listStu").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
